package com.zhoupu.integrated.file.service.impl;


import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.zhoupu.integrated.file.config.S3Config;
import com.zhoupu.integrated.file.service.IFileUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;

import java.io.ByteArrayInputStream;

@Service
public class FileUploadService implements IFileUploadService {

    @Autowired
    private S3Config s3Config;

    @Autowired
    private S3Client s3Client;


    @Override
    public String upload(byte[] content, String path, String originalName) {

        if (StrUtil.isEmpty(path)){
            path = generatePath(content,originalName);
        }

        // 执行上传
        PutObjectRequest putObjectRequest = PutObjectRequest.builder()
                .bucket(s3Config.getBucket())
                .key(path)
                .build();

        s3Client.putObject(putObjectRequest, RequestBody.fromBytes(content));

        // 拼接返回路径
        return s3Config.getDomain() + "/" + s3Config.getBucket() + path;
    }

    private static String generatePath(byte[] content, String originalName) {

        String sha256Hex = DigestUtil.sha256Hex(content);
        // 情况一：如果存在 name，则优先使用 name 的后缀
        if (StrUtil.isNotBlank(originalName)) {
            String extName = FileNameUtil.extName(originalName);
            return StrUtil.isBlank(extName) ? sha256Hex : sha256Hex + "." + extName;
        }
        // 情况二：基于 content 计算
        return sha256Hex + '.' + FileTypeUtil.getType(new ByteArrayInputStream(content));
    }

}

